﻿using FlashPay.DAO.Bank;
using FlashPay.DAO.Interface;
using FlashPay.DAO.Order;
using FlashPay.EF.Models;
using FlashPay.Entity.DAORequest.Bank;
using FlashPay.Entity.DAORequest.CardMerchant;
using FlashPay.Entity.DAORequest.User;
using FlashPay.Entity.Enum;
using FlashPay.Entity.LogAffect;
using FlashPay.Entity.Request.Order;
using FlashPay.Entity.Response.Order;
using FlashPay.Entity.Response.User;
using FlashPay.Service.Order;
using FlashPay.Service.Shared;
using FlashPay.Util;
using FlashPay.Util.StatusCode;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using System;
using System.Collections.Generic;
using System.Linq;

namespace FlashPay.Service.Impl.Order
{
    /// <summary>
    /// 訂單服務
    /// </summary>
    public class OrderSerivceImpl : BaseService, OrderService
    {
        private readonly OrderRecordDAO orderRecordDAO;
        private readonly OrderRecordDetailDao orderRecordDetailDAO;
        private readonly CardMerchantDao cardMerchantDAO;
        private readonly BankInfoDAO bankInfoDAO;
        private readonly BankCardDao bankCardDAO;
        private readonly DbContext dbContext;
        private readonly StatusCodeFactory statusCodeFactory;

        public OrderSerivceImpl(
            OrderRecordDAO orderRecordDAO,
            OrderRecordDetailDao orderRecordDetailDAO,
            CompanyDao companyDAO, 
            UserInfoDao userInfoDao,
            CardMerchantDao cardMerchantDAO,
            BankInfoDAO bankInfoDAO,
            BankCardDao bankCardDAO,
            LogDao logDao,
            StatusCodeFactory statusCodeFactory,
            DbContext dbContext,
            LogRecord logRecord)
        {
            this.orderRecordDAO = orderRecordDAO;
            this.orderRecordDetailDAO = orderRecordDetailDAO;
            this.companyDAO = companyDAO;
            this.userInfoDao = userInfoDao;
            this.cardMerchantDAO = cardMerchantDAO;
            this.bankInfoDAO = bankInfoDAO;
            this.bankCardDAO = bankCardDAO;
            this.logDao = logDao;
            this.dbContext = dbContext;
            this.logRecord = logRecord;
            this.statusCodeFactory = statusCodeFactory;
        }

        #region 映射轉換

        private OrderRecord MapperRequest<T>(OrderRecordRequest<T> model)
        {
            OrderRecord request = new OrderRecord();

            request.DeliveryNo = model.DeliveryNo;
            request.Cmid = model.CMID;

            if (model.OrderNo != null)
                request.OrderNo = (Int64)model.OrderNo;

            if (model.OrderDate != null)
                request.OrderDate = (DateTime)model.OrderDate;

            if (model.DepositUID != null)
                request.DepositUid = (Int32)model.DepositUID;

            if (model.DepositDate != null)
                request.DepositDate = (DateTime)model.DepositDate;

            if (model.DepositAmount != null)
                request.DepositAmount = (Decimal)model.DepositAmount;

            if (model.ReceiptDate != null)
                request.ReceiptDate = (DateTime)model.ReceiptDate;

            if (model.PayUID != null)
                request.PayUid = (Int32)model.PayUID;

            if (model.PayDate != null)
                request.PayDate = (DateTime)model.PayDate;

            if (model.PayAmount != null)
                request.PayAmount = (Decimal)model.PayAmount;

            if (model.CreateUID != null)
                request.CreateUid = (Int32)model.CreateUID;

            if (model.CreateDate != null)
                request.CreateDate = (DateTime)model.CreateDate;

            return request;
        }

        private OrderRecordResponse MapperResponse(OrderRecord model)
        {
            OrderRecordResponse response = new OrderRecordResponse();
            response.OrderNo = Convert.ToString(model.OrderNo);
            response.OrderDate = model.OrderDate;
            response.DeliveryNo = model.DeliveryNo;
            response.DepositUID = model.DepositUid;
            response.DepositDate = model.DepositDate;
            response.DepositAmount = model.DepositAmount;
            response.DepositCardNumber = model.DepositCardNumber;
            response.ReceiptDate = model.ReceiptDate;
            response.ReceiptUID = model.ReceiptUid;
            response.PayUID = model.PayUid;
            response.PayDate = model.PayDate;
            response.PayAmount = model.PayAmount;
            response.PayCardNumber = model.PayCardNumber;
            response.UserData = new Dictionary<int, UserResponse>();
            response.CreateUID = model.CreateUid;
            response.CreateDate = model.CreateDate;

            return response;
        }

        private OrderRecordDetail MapperRequest<T>(OrderRecordDetailRequest<T> model)
        {
            OrderRecordDetail request = new OrderRecordDetail();
            request.DetailId = model.DetailID;
            request.OrderNo = model.OrderNo;
            request.BankCode = model.BankCode;
            request.OrderQuantity = model.OrderQuantity;
            request.UnitPrice = model.UnitPrice;
            request.ActualQuantity = model.ActualQuantity;
            request.ActualUnitPrice = model.ActualUnitPrice;
            request.Remark = model.Remark;
            request.CreateUid = model.CreateUID;
            request.CreateDate = model.CreateDate;

            return request;
        }

        private OrderRecordDetailResponse MapperResponse(OrderRecordDetail model)
        {
            OrderRecordDetailResponse response = new OrderRecordDetailResponse();
            response.DetailID = model.DetailId;
            response.OrderNo = Convert.ToString(model.OrderNo);
            response.BankCode = model.BankCode;
            response.OrderQuantity = model.OrderQuantity;
            response.UnitPrice = model.UnitPrice.ToString("#0.00");
            response.ActualQuantity = model.ActualQuantity;
            response.ActualUnitPrice = model.ActualUnitPrice.ToString("#0.00");
            response.Remark = model.Remark;
            response.CreateUID = model.CreateUid;
            response.CreateDate = model.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"); ;

            return response;
        }

        #endregion

        /// <summary>
        /// 訂單及詳情新增
        /// </summary>
        public void AddOrderRecord(OrderRecordRequest<String> model)
        {
            using (orderRecordDAO)
            {
                /* Log相關資料 */
                SByte logLevel = (SByte)LogLevel.Error;
                Int32 logType = (Int32)LogRecordLogType.CardOrder_Add;
                String logRemark = "";

                /* 補上必要資料 */
                model.CreateDate = GetNowDateTime();

                /* 轉換Model */
                OrderRecord request = MapperRequest(model);

                LogAffectData data = new LogAffectData();

                /* 紀錄資料 */
                data.AfterData.Add("NewOrderData", CloneObject(request));

                try
                {
                    /* 呼叫DAO層 */
                    orderRecordDAO.Add(model, request);

                    /* 紀錄資料 */
                    data.BeforeData.Add("NewOrderData", request);

                    logLevel = (SByte)(model.Success ? LogLevel.Success : LogLevel.Failure);

                    /* 結果複製 */
                    model.Result = Convert.ToString(request.OrderNo);
                }
                catch (Exception e)
                {
                    logRemark = e.Message;
                    throw;
                }
                finally
                {
                    /* 新增Log */
                    AddLog(logLevel, logType, model, logRemark, data);
                }
            }
        }

        /// <summary>
        /// 訂單修改(押金審核後，能修改的部分只剩 收貨日期、付款日期 兩樣(另開接口))(付款審核後禁止修改)
        /// </summary>
        public void EditOrderRecord(OrderRecordRequest<String> model)
        {
            using (orderRecordDAO)
            {
                /* Log相關資料 */
                SByte logLevel = (SByte)LogLevel.Failure;
                Int32 logType = (Int32)LogRecordLogType.CardOrder_Update;
                String logRemark = "";

                LogAffectData data = new LogAffectData();

                try
                {
                    /* 獲取資料 */
                    OrderRecord request = GetOrderRecord((Int64)model.OrderNo);

                    /* 紀錄資料 */
                    data.AfterData.Add("OriginalOrderData", CloneObject(request));

                    /* 檢查資料 */
                    if (request == null)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_EDIT_CANNOT_FIND_DATA, model);
                        logRemark = model.Message;
                        return;
                    }
                    
                    /* 確認用戶關聯性 */
                    if (request.CreateUid != model.CreateUID && !CheckUserRelevance(request.CreateUid, model.CompanyID))
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_EDIT_NO_DATA_OWNERSHIP, model);
                        logRemark = model.Message;
                        return;
                    }
                    
                    /* 若押金已審核 */
                    if (request.DepositUid > 0)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_EDIT_DEPOSIT_PASSED, model);
                        logRemark = model.Message;
                        return;
                    }
                    
                    /* 若付款已審核 */
                    if (request.PayUid > 0)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_EDIT_PAY_PASSED, model);
                        logRemark = model.Message;
                        return;
                    }

                    request.Cmid = model.CMID;
                    request.DeliveryNo = model.DeliveryNo;

                    //if (model.ReceiptDate != null)
                    //{
                    //    request.ReceiptDate = (DateTime)model.ReceiptDate;
                    //}

                    //if (model.PayDate != null)
                    //{
                    //    request.PayDate = (DateTime)model.PayDate;
                    //}

                    //if (model.DepositDate != null)
                    //{
                    //    request.DepositDate = (DateTime)model.DepositDate;
                    //}  

                    if (model.OrderDate != null)
                    {
                        request.OrderDate = (DateTime)model.OrderDate;
                    }

                    List<int> cardIds = new List<int> { request.Cmid };
                    bool isCheckCard = CheckCardUser(cardIds, model.LoginUserID);

                    //有查看所有订单相关金额的权限,才可以修改
                    if (model.Code != Entity.AuthCode.Order0017.ToString() || isCheckCard || (request.CreateUid == model.CreateUID))
                    {
                        if (model.DepositAmount != null && model.DepositAmount > 0)
                        {
                            request.DepositAmount = (Decimal)model.DepositAmount;
                        }
                    }

                    /* 呼叫DAO層 */
                    orderRecordDAO.EditUseOrderNo(model, request);

                    /* 紀錄資料 */
                    data.BeforeData.Add("ModifiedOrderData", request);

                    if (model.Success)
                    {
                        logLevel = (SByte)LogLevel.Success;
                    }
                }
                catch (Exception e)
                {
                    logLevel = (SByte)LogLevel.Error;
                    logRemark = e.Message;
                    throw;
                }
                finally
                {
                    /* 新增Log */
                    AddLog(logLevel, logType, model, logRemark, data);
                }
            }
        }

        /// <summary>
        /// 收貨時間修改(暫且隱藏)
        /// </summary>
        public void EditOrderRecordReceiptDate(OrderRecordRequest<String> model)
        {
            return;
            using (orderRecordDAO)
            {
                /* Log相關資料 */
                SByte logLevel = (SByte)LogLevel.Failure;
                Int32 logType = (Int32)LogRecordLogType.CardOrder_Update;
                String logRemark = "";

                LogAffectData data = new LogAffectData();

                try
                {
                    /* 獲取資料 */
                    OrderRecord request = GetOrderRecord((Int64)model.OrderNo);

                    /* 紀錄資料 */
                    data.AfterData.Add("OriginalOrderData", CloneObject(request));

                    /* 檢查資料 */
                    if (request == null)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_EDIT_RECEIPT_DATE_CANNOT_FIND_DATA, model);
                        logRemark = model.Message;
                        return;
                    }

                    /* 確認用戶關聯性 */
                    if (request.CreateUid != model.CreateUID && !CheckUserRelevance(request.CreateUid, model.CompanyID))
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_EDIT_RECEIPT_DATE_NO_DATA_OWNERSHIP, model);
                        logRemark = model.Message;
                        return;
                    }

                    /* 若付款已審核 */
                    if (request.PayUid > 0)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_EDIT_RECEIPT_DATE_PAY_PASSED, model);
                        logRemark = model.Message;
                        return;
                    }

                    request.ReceiptDate = (DateTime)model.ReceiptDate;

                    /* 呼叫DAO層 */
                    orderRecordDAO.EditUseOrderNo(model, request);

                    /* 紀錄資料 */
                    data.BeforeData.Add("ModifiedOrderData", request);

                    if (model.Success)
                    {
                        logLevel = (SByte)LogLevel.Success;
                    }
                }
                catch (Exception e)
                {
                    logLevel = (SByte)LogLevel.Error;
                    logRemark = e.Message;
                    throw;
                }
                finally
                {
                    /* 新增Log */
                    AddLog(logLevel, logType, model, logRemark, data);
                }
            }
        }

        /// <summary>
        /// 付款時間修改(暫且隱藏)
        /// </summary>
        public void EditOrderRecordPayDate(OrderRecordRequest<String> model)
        {
            return;
            using (orderRecordDAO)
            {
                /* Log相關資料 */
                SByte logLevel = (SByte)LogLevel.Failure;
                Int32 logType = (Int32)LogRecordLogType.CardOrder_Update;
                String logRemark = "";

                LogAffectData data = new LogAffectData();

                try
                {
                    /* 獲取資料 */
                    OrderRecord request = GetOrderRecord((Int64)model.OrderNo);

                    /* 紀錄資料 */
                    data.AfterData.Add("OriginalOrderData", CloneObject(request));

                    /* 檢查資料 */
                    if (request == null)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_EDIT_PAY_DATE_CANNOT_FIND_DATA, model);
                        logRemark = model.Message;
                        return;
                    }

                    /* 確認用戶關聯性 */
                    if (request.CreateUid != model.CreateUID && !CheckUserRelevance(request.CreateUid, model.CompanyID))
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_EDIT_PAY_DATE_NO_DATA_OWNERSHIP, model);
                        logRemark = model.Message;
                        return;
                    }

                    /* 若付款已審核 */
                    if (request.PayUid > 0)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_EDIT_PAY_DATE_PAY_PASSED, model);
                        logRemark = model.Message;
                        return;
                    }

                    request.PayDate = (DateTime)model.PayDate;

                    /* 呼叫DAO層 */
                    orderRecordDAO.EditUseOrderNo(model, request);

                    /* 紀錄資料 */
                    data.BeforeData.Add("ModifiedOrderData", request);

                    if (model.Success)
                    {
                        logLevel = (SByte)LogLevel.Success;
                    }
                }
                catch (Exception e)
                {
                    logLevel = (SByte)LogLevel.Error;
                    logRemark = e.Message;
                    throw;
                }
                finally
                {
                    /* 新增Log */
                    AddLog(logLevel, logType, model, logRemark, data);
                }
            }
        }

        /// <summary>
        /// 貨運單號修改
        /// </summary>
        public void EditOrderRecordDeliveryNo(OrderRecordRequest<String> model)
        {
            using (orderRecordDAO)
            {
                /* Log相關資料 */
                SByte logLevel = (SByte)LogLevel.Failure;
                Int32 logType = (Int32)LogRecordLogType.CardOrder_Update;
                String logRemark = "";

                LogAffectData data = new LogAffectData();

                try
                {
                    /* 獲取資料 */
                    OrderRecord request = GetOrderRecord((Int64)model.OrderNo);

                    /* 紀錄資料 */
                    data.AfterData.Add("OriginalOrderData", CloneObject(request));

                    /* 檢查資料 */
                    if (request == null)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_EDIT_PAY_DATE_CANNOT_FIND_DATA, model);
                        logRemark = model.Message;
                        return;
                    }

                    /* 確認用戶關聯性 */
                    if (request.CreateUid != model.CreateUID && !CheckUserRelevance(request.CreateUid, model.CompanyID))
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_EDIT_PAY_DATE_NO_DATA_OWNERSHIP, model);
                        logRemark = model.Message;
                        return;
                    }

                    /* 若付款已審核 */
                    if (request.PayUid > 0)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_EDIT_PAY_DATE_PAY_PASSED, model);
                        logRemark = model.Message;
                        return;
                    }

                    request.DeliveryNo = model.DeliveryNo;

                    /* 呼叫DAO層 */
                    orderRecordDAO.EditUseOrderNo(model, request);

                    /* 紀錄資料 */
                    data.BeforeData.Add("ModifiedOrderData", request);

                    if (model.Success)
                    {
                        logLevel = (SByte)LogLevel.Success;
                    }
                }
                catch (Exception e)
                {
                    logLevel = (SByte)LogLevel.Error;
                    logRemark = e.Message;
                    throw;
                }
                finally
                {
                    /* 新增Log */
                    AddLog(logLevel, logType, model, logRemark, data);
                }
            }
        }

        /// <summary>
        /// 訂單刪除(押金審核後禁止刪除)
        /// </summary>
        public void DeleteOrderRecord(OrderRecordRequest<String> model)
        {
            using (orderRecordDAO)
            {
                /* Log相關資料 */
                SByte logLevel = (SByte)LogLevel.Failure;
                Int32 logType = (Int32)LogRecordLogType.CardOrder_Delete;
                String logRemark = "";

                LogAffectData data = new LogAffectData();

                try
                {
                    /* 獲取資料 */
                    OrderRecord request = GetOrderRecord((Int64)model.OrderNo);

                    /* 紀錄資料 */
                    data.AfterData.Add("OriginalOrderData", CloneObject(request));

                    /* 檢查資料 */
                    if (request == null)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_DELETE_CANNOT_FIND_DATA, model);
                        logRemark = model.Message;
                        return;
                    }

                    /* 確認用戶關聯性 */
                    if (request.CreateUid != model.CreateUID && !CheckUserRelevance(request.CreateUid, model.CompanyID))
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_DELETE_NO_DATA_OWNERSHIP, model);
                        logRemark = model.Message;
                        return;
                    }

                    /* 若押金已審核 */
                    if (request.DepositUid > 0)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_DELETE_DEPOSIT_PASSED, model);
                        logRemark = model.Message;
                        return;
                    }

                    /* 呼叫DAO層 */
                    orderRecordDAO.DeleteUseOrderNo(model, request);

                    /* 紀錄資料 */
                    data.BeforeData.Add("ModifiedOrderData", request);

                    if (model.Success)
                    {
                        logLevel = (SByte)LogLevel.Success;
                    }
                }
                catch (Exception e)
                {
                    logLevel = (SByte)LogLevel.Error;
                    logRemark = e.Message;
                    throw;
                }
                finally
                {
                    /* 新增Log */
                    AddLog(logLevel, logType, model, logRemark, data);
                }
            }
        }

        /// <summary>
        /// 訂單列表(需要優化)
        /// </summary>
        public void GetOrderRecord(OrderRecordRequest<List<OrderRecordResponse>> model)
        {
            using (orderRecordDAO)
            {
                /* 準備資料 */
                UserRequest request2 = new UserRequest();
                BaseModel<List<UserInfo>> model2 = new BaseModel<List<UserInfo>>();
                model2.PageSize = Int32.MaxValue;
                
                List<Int32> userId = GetRelatedUser(model.CompanyID);
                if (model.UserPermission!=null && model.UserPermission.Contains("Order0018")) {
                    var user = userInfoDao.Get(model.UserId);
                    if (user != null && user.UCreateId>0) {
                        userId.Add(user.UCreateId);
                    }
                }
                /* 檢查資料 */
                if (userId == null)
                {
                    return;
                }

                if (userId.Count == 0)
                {
                    model.Success = true;
                    model.Result = new List<OrderRecordResponse>();
                    return;
                }

                /* 轉換Model */
                Entity.DAORequest.Order.OrderRecordRequest request = new Entity.DAORequest.Order.OrderRecordRequest();
                request.OrderNo = model.OrderNo;
                request.OrderDate = model.OrderDate;
                request.EndOrderDate = model.EndOrderDate;
                request.PayDate = model.PayDate;
                request.EndPayDate = model.EndPayDate;

                if (!String.IsNullOrEmpty(model.CMName))
                {
                    BaseModel<List<CardMerchant>> model4 = new BaseModel<List<CardMerchant>>();
                    CardMerchantRequest request4 = new CardMerchantRequest();
                    request4.CMName = model.CMName;//卡商名称
                    /* 呼叫DAO層 */
                    cardMerchantDAO.Get(model4, request4);

                    /* 檢查資料 */
                    if (!model4.Success)
                    {
                        return;
                    }
                    if (model4.Result.Count == 0)
                    {
                        model.Success = true;
                        model.Result = new List<OrderRecordResponse>();
                        return;
                    }
                    request.CMID = model4.Result.Select(data => data.Cmid).ToList();
                }

                request.DeliveryNo = model.DeliveryNo;//快递单号
                request.Status = model.Status;
                request.CreateUID = userId;

                /* 人名搜索 */
                /* 之後要優化 */
                if (!String.IsNullOrEmpty(model.PayUserName))
                {
                    request2.UserName = model.PayUserName;

                    /* 呼叫DAO層 */
                    userInfoDao.Get(model2, request2);

                    if (!model2.Success)
                    {
                        return;
                    }

                    if (model2.Result.Count == 0)
                    {
                        model.Success = true;
                        model.Result = new List<OrderRecordResponse>();
                        return;
                    }

                    request.PayUID = model2.Result.Select(data => data.UId).ToList();
                    request.DepositUID = request.PayUID;

                    /* 恢復預設內容 */
                    request2.UserName = null;
                }

                BaseModel<List<OrderRecord>> model3 = new BaseModel<List<OrderRecord>>
                {
                    PageIndex = model.PageIndex,
                    PageSize = model.PageSize
                };

                /* 呼叫DAO層 */
                orderRecordDAO.Get(model3, request);

                if (!model3.Success)
                {
                    return;
                }

                /* 關聯用戶資料 */
                /* 之後要優化 */
                HashSet<Int32> UserID = new HashSet<Int32>();
                foreach (OrderRecord __model in model3.Result)
                {
                    UserID.Add(__model.DepositUid);
                    UserID.Add(__model.ReceiptUid);
                    UserID.Add(__model.PayUid);
                }
                request2.UserID = new List<Int32>(UserID);

                /* 呼叫DAO層 */
                userInfoDao.Get(model2, request2);

                if (!model2.Success)
                {
                    return;
                }

                Dictionary<Int32, UserResponse> UserData = new Dictionary<int, UserResponse>();
                foreach (UserInfo info in model2.Result)
                {
                    UserData.Add(info.UId, new UserResponse() {
                        UserID = info.UId,
                        UserName = info.ULoginName
                    });
                }

                BaseModel<List<CardMerchant>> model5 = new BaseModel<List<CardMerchant>>();
                CardMerchantRequest request5 = new CardMerchantRequest();
                //request5.CMID = model3.Result.Select(d => d.Cmid).ToList();
                request5.CMName = model.CMName;//卡商名称
                /* 呼叫DAO層 */
                model5.PageSize = 1000;
                cardMerchantDAO.Get(model5, request5);

                /* 檢查資料 */
                if (!model5.Success)
                {
                    return;
                }

                Dictionary<Int32, String> card = new Dictionary<int, string>();
                Dictionary<int, int> cardManager = new Dictionary<int, int>();
                foreach (CardMerchant cardMerchant in model5.Result)
                {
                    card.Add(cardMerchant.Cmid, cardMerchant.Cmname);
                    cardManager.Add(cardMerchant.Cmid, cardMerchant.CreateUid);
                }

                /* 轉換Model */
                OrderRecordResponse temp;
                List<OrderRecordResponse> result = new List<OrderRecordResponse>();
                foreach (OrderRecord __model in model3.Result)
                {
                    temp = MapperResponse(__model);

                    if (__model.DepositUid > 0 && UserData.ContainsKey(__model.DepositUid) && !temp.UserData.ContainsKey(__model.DepositUid))
                    {
                        temp.UserData.Add(__model.DepositUid, UserData[__model.DepositUid]);
                    }

                    if (__model.PayUid > 0 && UserData.ContainsKey(__model.PayUid) && !temp.UserData.ContainsKey(__model.PayUid))
                    {
                        temp.UserData.Add(__model.PayUid, UserData[__model.PayUid]);
                    }

                    if (__model.ReceiptUid > 0 && UserData.ContainsKey(__model.ReceiptUid) && !temp.UserData.ContainsKey(__model.ReceiptUid))
                    {
                        temp.UserData.Add(__model.ReceiptUid, UserData[__model.ReceiptUid]);
                    }

                    if (card.ContainsKey(__model.Cmid))
                    {
                        temp.CardMerchantName = card[__model.Cmid];
                    }
                    if (card.ContainsKey(__model.Cmid))
                    {
                        temp.CardMerchantUID = cardManager[__model.Cmid];
                    }

                    //计算付款金额
                    OrderRecordDetail detailOrder = new OrderRecordDetail() { OrderNo = __model.OrderNo };
                    List<OrderRecordDetail> detailList = GetOrderRecordDetails(detailOrder);
                    decimal totalPrice = 0;
                    for (int j = 0;detailList!=null && detailList.Count>0 && j < detailList.Count; j++)
                    {
                        totalPrice += detailList[j].ActualQuantity * detailList[j].ActualUnitPrice;
                    }
                    temp.PayAmount = totalPrice;
                    //计算付款金额 end
                    result.Add(temp);
                }

                /* 結果複製 */
                model.Result = result;
                model.Success = model3.Success;
                model.TotalCount = model3.TotalCount;
            }
        }

        /// <summary>
        /// 訂單相關人員ID
        /// </summary>
        public void GetAllOrderRecordUserId(OrderRecordRequest<List<Int32>> model)
        {
            List<Int32> userId = GetRelatedUser(model.CompanyID);

            /* 檢查資料 */
            if (userId == null)
            {
                statusCodeFactory.BuildStatus(StatusCode.SYSTEM_ERROR, model);
                return;
            }

            if (userId.Count == 0)
            {
                model.Success = true;
                model.Result = new List<Int32>();
                return;
            }

            /* 轉換Model */
            Entity.DAORequest.Order.OrderRecordRequest request = new Entity.DAORequest.Order.OrderRecordRequest();
            request.CreateUID = userId;

            BaseModel<List<OrderRecord>> model2 = new BaseModel<List<OrderRecord>>();
            model2.PageSize = Int32.MaxValue;

            /* 呼叫DAO層 */
            orderRecordDAO.Get(model2, request);

            if (!model2.Success)
            {
                statusCodeFactory.BuildStatus(StatusCode.SYSTEM_ERROR, model);
                return;
            }

            HashSet<Int32> ids = new HashSet<Int32>();
            foreach (OrderRecord o in model2.Result)
            {
                ids.Add(o.PayUid);
                ids.Add(o.DepositUid);
            }
            
            /* 結果複製 */
            model.Result = ids.ToList();
            model.Success = model2.Success;
        }

        /// <summary>
        /// 押金審核
        /// </summary>
        public void PassOrderRecordDeposit(OrderRecordRequest<String> model)
        {
            using (orderRecordDAO)
            {
                /* Log相關資料 */
                SByte logLevel = (SByte)LogLevel.Failure;
                Int32 logType = (Int32)LogRecordLogType.CardOrder_DepositConfirm;
                String logRemark = "";

                LogAffectData data = new LogAffectData();

                try
                {
                    #region 驗證訂單

                    /* 獲取資料 */
                    OrderRecord request = GetOrderRecord((Int64)model.OrderNo);

                    /* 紀錄資料 */
                    AddAffectData(data.AfterData, "OriginalOrderData", request);

                    /* 檢查資料 */
                    if (request == null)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_PASS_DEPOSIT_CANNOT_FIND_DATA, model);
                        logRemark = model.Message;
                        return;
                    }

                    /* 確認用戶關聯性 */
                    if (request.CreateUid != model.DepositUID && !CheckUserRelevance(request.CreateUid, model.CompanyID))
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_PASS_DEPOSIT_NO_DATA_OWNERSHIP, model);
                        logRemark = model.Message;
                        return;
                    }

                    /* 若押金已審核 */
                    if (request.DepositUid > 0)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_PASS_DEPOSIT_DEPOSIT_PASSED, model);
                        logRemark = model.Message;
                        return;
                    }

                    #endregion

                    #region 驗證子訂單

                    /* 若子訂單為空 */
                    OrderRecordDetail request2 = new OrderRecordDetail();
                    request2.OrderNo = request.OrderNo;

                    Int32? count = GetOrderRecordDetailCount(request2);

                    data.AfterData.Add("SubOrderCount", count);

                    if (count == null)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.SYSTEM_ERROR, model);
                        logRemark = model.Message;
                        return;
                    }

                    if (count.Value == 0)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_PASS_DEPOSIT_NO_SUB_ORDER, model);
                        logRemark = model.Message;
                        return;
                    }

                    #endregion

                    /* 補上資料 */
                    request.DepositUid = (Int32)model.DepositUID;
                    request.DepositCardNumber = model.DepositCardNumber;
                    request.DepositDate = GetNowDateTime();

                    /* 呼叫DAO層 */
                    orderRecordDAO.EditUseOrderNo(model, request);

                    /* 紀錄資料 */
                    AddAffectData(data.BeforeData, "ModifiedOrderData", request);

                    if (model.Success)
                    {
                        logLevel = (SByte)LogLevel.Success;
                    }
                }
                catch (Exception e)
                {
                    logLevel = (SByte)LogLevel.Error;
                    logRemark = e.Message;
                    throw;
                }
                finally
                {
                    /* 新增Log */
                    AddLog(logLevel, logType, model, logRemark, data);
                }
            }
        }

        /// <summary>
        /// 收貨審核(必須先通過押金審核)
        /// </summary>
        public void PassOrderRecordReceipt(OrderRecordRequest<String> model)
        {
            using (orderRecordDAO)
            {
                /* Log相關資料 */
                SByte logLevel = (SByte)LogLevel.Failure;
                Int32 logType = (Int32)LogRecordLogType.CardOrder_ReceiptConfirm;
                String logRemark = "";

                LogAffectData data = new LogAffectData();

                try
                {
                    #region 驗證訂單

                    /* 獲取資料 */
                    OrderRecord request = GetOrderRecord((Int64)model.OrderNo);

                    /* 紀錄資料 */
                    AddAffectData(data.AfterData, "OriginalOrderData", request);

                    /* 檢查資料 */
                    if (request == null)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_PASS_DEPOSIT_CANNOT_FIND_DATA, model);
                        logRemark = model.Message;
                        return;
                    }

                    /* 確認用戶關聯性 */
                    if (request.CreateUid != model.DepositUID && !CheckUserRelevance(request.CreateUid, model.CompanyID))
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_PASS_DEPOSIT_NO_DATA_OWNERSHIP, model);
                        logRemark = model.Message;
                        return;
                    }

                    /* 若押金未審核 */
                    if (request.DepositUid == 0)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_PASS_PAY_DEPOSIT_NO_PASS, model);
                        logRemark = model.Message;
                        return;
                    }

                    /* 若收貨已審核 */
                    if (request.ReceiptUid > 0)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_PASS_RECEIPT_RECEIPT_PASSED, model);
                        logRemark = model.Message;
                        return;
                    }

                    #endregion

                    #region 驗證子訂單

                    /* 驗證是否可以審核通過 */
                    OrderRecordDetail request2 = new OrderRecordDetail();
                    request2.OrderNo = request.OrderNo;

                    List<OrderRecordDetail> details = GetOrderRecordDetails(request2);

                    /* 紀錄資料 */
                    AddAffectData(data.AfterData, "OriginalOrderDetailData", details);

                    /* 檢查資料 */
                    if (details == null)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.SYSTEM_ERROR, model);
                        logRemark = model.Message;
                        return;
                    }

                    /*如果子订单数量为0*/
                    if (details.Count == 0)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_PASS_DEPOSIT_NO_SUB_ORDER, model);
                        logRemark = model.Message;
                        return;
                    }

                    /* 計算各銀行卡數量 */
                    Dictionary<String, Int32> card = new Dictionary<String, Int32>();
                    foreach (OrderRecordDetail d in details)
                    {
                        if (card.ContainsKey(d.BankCode))
                        {
                            card[d.BankCode] += d.ActualQuantity;
                        }
                        else
                        {
                            card.Add(d.BankCode, d.ActualQuantity);
                        }
                    }

                    if (card.FirstOrDefault().Value == 0)
                    {
                        model.Message = "收货失败,订单实际价格不能为0";
                        logRemark = model.Message;
                        return;
                    }

                    List<BankCard> bankCards = GetBankCards(request.OrderNo);
                    if (bankCards.Count == 0 && details.Count > 0)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_PASS_PAY_BANK_CARD_DATA_NOT_MATCH, model);
                        logRemark = model.Message;
                        return;
                    }

                    /* 紀錄資料 */
                    data.AfterData.Add("OriginalBankCardData", bankCards);

                    foreach (BankCard b in bankCards)
                    {
                        if (card.ContainsKey(b.BankCode))
                        {
                            card[b.BankCode]--;
                        }
                        else
                        {
                            statusCodeFactory.BuildStatus(StatusCode.ORDER_PASS_PAY_BANK_CARD_DATA_NOT_MATCH, model);
                            logRemark = model.Message;
                            return;
                        }
                    }

                    foreach (KeyValuePair<String, Int32> kv in card)
                    {
                        if (kv.Value != 0)
                        {
                            statusCodeFactory.BuildStatus(StatusCode.ORDER_PASS_PAY_BANK_CARD_DATA_NOT_MATCH, model);
                            logRemark = model.Message;
                            return;
                        }
                    }

                    #endregion

                    /* 補上資料 */
                    request.ReceiptUid = (Int32)model.ReceiptUID;
                    request.ReceiptDate = GetNowDateTime();

                    /* 呼叫DAO層 */
                    orderRecordDAO.EditUseOrderNo(model, request);

                    /* 紀錄資料 */
                    AddAffectData(data.BeforeData, "ModifiedOrderData", request);

                    if (model.Success)
                    {
                        logLevel = (SByte)LogLevel.Success;
                    }
                }
                catch (Exception e)
                {
                    logLevel = (SByte)LogLevel.Error;
                    logRemark = e.Message;
                    throw;
                }
                finally
                {
                    /* 新增Log */
                    AddLog(logLevel, logType, model, logRemark, data);
                }
            }
        }

        /// <summary>
        /// 付款審核(必須先通過收貨審核)
        /// </summary>
        public void PassOrderRecordPay(OrderRecordRequest<String> model)
        {
            using (orderRecordDAO)
            {
                /* Log相關資料 */
                SByte logLevel = (SByte)LogLevel.Failure;
                Int32 logType = (Int32)LogRecordLogType.CardOrder_PayConfirm;
                String logRemark = "";

                LogAffectData data = new LogAffectData();

                try
                {
                    #region 驗證訂單

                    /* 獲取資料 */
                    OrderRecord request = GetOrderRecord((Int64)model.OrderNo);

                    /* 紀錄資料 */
                    AddAffectData(data.AfterData, "OriginalOrderData", request);

                    /* 檢查資料 */
                    if (request == null)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_PASS_PAY_CANNOT_FIND_DATA, model);
                        logRemark = model.Message;
                        return;
                    }

                    /* 確認用戶關聯性 */
                    if (request.CreateUid != model.PayUID && !CheckUserRelevance(request.CreateUid, model.CompanyID))
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_PASS_PAY_NO_DATA_OWNERSHIP, model);
                        logRemark = model.Message;
                        return;
                    }

                    /* 若押金未審核 */
                    if (request.DepositUid == 0)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_PASS_PAY_DEPOSIT_NO_PASS, model);
                        logRemark = model.Message;
                        return;
                    }

                    /* 若收貨未審核 */
                    if (request.ReceiptUid == 0)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_PASS_PAY_RECEIPT_NO_PASS, model);
                        logRemark = model.Message;
                        return;
                    }

                    /* 若付款已審核 */
                    if (request.PayUid > 0)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_PASS_PAY_PAY_PASSED, model);
                        logRemark = model.Message;
                        return;
                    }

                    #endregion
                    
                    request.PayUid = (Int32)model.PayUID;
                    request.PayCardNumber = model.PayCardNumber;
                    request.PayDate = GetNowDateTime();

                    /* 呼叫DAO層 */
                    orderRecordDAO.EditUseOrderNo(model, request);

                    /* 紀錄資料 */
                    AddAffectData(data.BeforeData, "ModifiedOrderData", request);

                    if (model.Success)
                    {
                        logLevel = (SByte)LogLevel.Success;
                    }
                }
                catch (Exception e)
                {
                    logLevel = (SByte)LogLevel.Error;
                    logRemark = e.Message;
                    throw;
                }
                finally
                {
                    /* 新增Log */
                    AddLog(logLevel, logType, model, logRemark, data);
                }
            }
        }

        /// <summary>
        /// 訂單詳情新增
        /// </summary>
        public void AddOrderRecordDetail(OrderRecordDetailRequest<String> model)
        {
            using (var transaction = BeginTransaction())
            using (orderRecordDetailDAO)
            {
                /* Log相關資料 */
                SByte logLevel = (SByte)LogLevel.Failure;
                Int32 logType = (Int32)LogRecordLogType.CardOrder_Child_Add;
                String logRemark = "";

                LogAffectData data = new LogAffectData();

                try
                {
                    #region 驗證訂單

                    /* 獲取訂單資料 */
                    OrderRecord request2 = GetOrderRecord(model.OrderNo);

                    /* 紀錄資料 */
                    AddAffectData(data.AfterData, "OriginalOrderData", request2);

                    /* 檢查資料 */
                    if (request2 == null)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_DETAIL_ADD_CANNOT_FIND_DATA, model);
                        logRemark = model.Message;
                        return;
                    }

                    /* 確認用戶關聯性 */
                    if (request2.CreateUid != model.CreateUID && !CheckUserRelevance(request2.CreateUid, model.CompanyID))
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_DETAIL_ADD_NO_DATA_OWNERSHIP, model);
                        logRemark = model.Message;
                        return;
                    }

                    /* 訂單完成後無法新增子訂單 */
                    if (request2.PayUid > 0)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_DETAIL_ADD_ORDER_HAS_BEEN_COMPLETED, model);
                        logRemark = model.Message;
                        return;
                    }

                    #endregion

                    #region 新增子訂單

                    /* 補上必要資料 */
                    model.CreateDate = GetNowDateTime();

                    /* 押金審核後只能補單 */
                    if (request2.DepositUid > 0)
                    {
                        model.OrderQuantity = 0;
                        model.UnitPrice = 0;
                    }

                    /* 轉換Model */
                    OrderRecordDetail request = MapperRequest(model);

                    /* 紀錄資料 */
                    data.AfterData.Add("NewOrderDetailData", CloneObject(request));

                    /* 呼叫DAO層 */
                    orderRecordDetailDAO.Add(model, request);

                    /* 檢查資料 */
                    if (!model.Success)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.SYSTEM_ERROR, model);
                        logRemark = model.Message;
                        return;
                    }

                    /* 紀錄資料 */
                    AddAffectData(data.BeforeData, "NewOrderDetailData", request);

                    #endregion

                    #region 更新訂單金額

                    /* 更新訂單 */
                    model.Success = EditOrderRecordPayAmount(request2, model.ActualQuantity * model.ActualUnitPrice * -1);

                    /* 紀錄資料 */
                    AddAffectData(data.BeforeData, "ModifiedOrderData", request2);

                    #endregion

                    /* 檢查資料 */
                    if (model.Success)
                    {
                        logLevel = (SByte)LogLevel.Success;
                        transaction.Commit();
                    }
                    else
                    {
                        transaction.Rollback();
                    }
                }
                catch (Exception e)
                {
                    logLevel = (SByte)LogLevel.Error;
                    logRemark = e.Message;
                    transaction.Rollback();
                    throw;
                }
                finally
                {
                    /* 新增Log */
                    AddLog(logLevel, logType, model, logRemark, data);
                }
            }
        }

        /// <summary>
        /// 訂單詳情修改(押金審核後，能修改的部分只剩 實際數量、實際單價 兩樣(另開接口))(付款審核後禁止修改)
        /// </summary>
        public void EditOrderRecordDetail(OrderRecordDetailRequest<String> model)
        {
            using (var transaction = BeginTransaction())
            using (orderRecordDetailDAO)
            {
                /* Log相關資料 */
                SByte logLevel = (SByte)LogLevel.Failure;
                Int32 logType = (Int32)LogRecordLogType.CardOrder_Child_Update;
                String logRemark = "";

                LogAffectData data = new LogAffectData();

                try
                {
                    #region 驗證子訂單

                    /* 獲取訂單詳情資料 */
                    OrderRecordDetail request = GetOrderRecordDetail(model.DetailID);

                    /* 紀錄資料 */
                    AddAffectData(data.AfterData, "OriginalOrderDetailData", request);

                    /* 檢查資料 */
                    if (request == null)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_DETAIL_EDIT_CANNOT_FIND_DATA, model);
                        logRemark = model.Message;
                        return;
                    }
                    
                    /* 確認用戶關聯性 */
                    if (request.CreateUid != model.CreateUID && !CheckUserRelevance(request.CreateUid, model.CompanyID))
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_DETAIL_EDIT_NO_DATA_OWNERSHIP, model);
                        logRemark = model.Message;
                        return;
                    }

                    #endregion

                    #region 驗證訂單

                    /* 獲取訂單資料 */
                    OrderRecord request2 = GetOrderRecord(request.OrderNo);

                    /* 紀錄資料 */
                    AddAffectData(data.AfterData, "OriginalOrderData", request2);

                    /* 檢查資料 */
                    if (request2 == null)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_DETAIL_EDIT_CANNOT_FIND_DATA, model);
                        logRemark = model.Message;
                        return;
                    }

                    /* 若押金已審核 */
                    if (request2.DepositUid > 0)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_DETAIL_EDIT_DEPOSIT_PASSED, model);
                        logRemark = model.Message;
                        return;
                    }

                    /* 若付款已審核 */
                    if (request2.PayUid > 0)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_DETAIL_EDIT_PAY_PASSED, model);
                        logRemark = model.Message;
                        return;
                    }

                    #endregion

                    #region 更新子訂單

                    Decimal originalPrice = request.ActualQuantity * request.ActualUnitPrice;
                    Decimal newPrice = model.ActualQuantity * model.ActualUnitPrice;

                    request.ActualQuantity = model.ActualQuantity;
                    request.ActualUnitPrice = model.ActualUnitPrice;
                    request.BankCode = model.BankCode;
                    request.OrderQuantity = model.OrderQuantity;
                    request.UnitPrice = model.UnitPrice;
                    request.Remark = model.Remark;

                    /* 呼叫DAO層 */
                    orderRecordDetailDAO.EditUseDetailId(model, request);

                    /* 紀錄資料 */
                    AddAffectData(data.BeforeData, "ModifiedOrderDetailData", request);

                    /* 檢查資料 */
                    if (!model.Success)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.SYSTEM_ERROR, model);
                        logRemark = model.Message;
                        return;
                    }

                    #endregion

                    #region 更新訂單金額

                    /* 更新訂單付款金額 */
                    if (originalPrice != newPrice)
                    {
                        model.Success = EditOrderRecordPayAmount(request2, originalPrice - newPrice);
                    }

                    /* 紀錄資料 */
                    AddAffectData(data.BeforeData, "ModifiedOrderData", request2);

                    #endregion

                    /* 檢查資料 */
                    if (model.Success)
                    {
                        logLevel = (SByte)LogLevel.Success;
                        transaction.Commit();
                    }
                    else
                    {
                        transaction.Rollback();
                    }
                }
                catch (Exception e)
                {
                    logLevel = (SByte)LogLevel.Error;
                    logRemark = e.Message;
                    transaction.Rollback();
                    throw;
                }
                finally
                {
                    /* 新增Log */
                    AddLog(logLevel, logType, model, logRemark, data);
                }
            }
        }

        /// <summary>
        /// 訂單詳情實際數量、實際單價修改(付款審核後禁止修改)
        /// </summary>
        public void EditOrderRecordDetailActualCountAndUnitPrice(OrderRecordDetailRequest<String> model)
        {
            using (var transaction = BeginTransaction())
            using (orderRecordDetailDAO)
            {
                /* Log相關資料 */
                SByte logLevel = (SByte)LogLevel.Failure;
                Int32 logType = (Int32)LogRecordLogType.CardOrder_Child_Update;
                String logRemark = "";

                LogAffectData data = new LogAffectData();

                try
                {
                    #region 驗證子訂單

                    /* 獲取訂單詳情資料 */
                    OrderRecordDetail request = GetOrderRecordDetail(model.DetailID);

                    /* 紀錄資料 */
                    AddAffectData(data.AfterData, "OriginalOrderDetailData", request);

                    /* 檢查資料 */
                    if (request == null)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_DETAIL_EDIT_ACTUAL_COUNT_AND_UNIT_PRICE_CANNOT_FIND_DATA, model);
                        logRemark = model.Message;
                        return;
                    }
                    
                    /* 確認用戶關聯性 */
                    if (request.CreateUid != model.CreateUID && !CheckUserRelevance(request.CreateUid, model.CompanyID))
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_DETAIL_EDIT_ACTUAL_COUNT_AND_UNIT_PRICE_NO_DATA_OWNERSHIP, model);
                        logRemark = model.Message;
                        return;
                    }

                    #endregion

                    #region 驗證訂單

                    /* 獲取訂單資料 */
                    OrderRecord request2 = GetOrderRecord(request.OrderNo);

                    /* 紀錄資料 */
                    AddAffectData(data.AfterData, "OriginalOrderData", request2);

                    /* 檢查資料 */
                    if (request2 == null)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_DETAIL_EDIT_ACTUAL_COUNT_AND_UNIT_PRICE_CANNOT_FIND_DATA, model);
                        return;
                    }

                    /* 若付款已審核 */
                    if (request2.PayUid > 0)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_DETAIL_EDIT_ACTUAL_COUNT_AND_UNIT_PRICE_PAY_PASSED, model);
                        return;
                    }

                    #endregion

                    #region 更新子訂單

                    Decimal originalPrice = request.ActualQuantity * request.ActualUnitPrice;
                    Decimal newPrice = model.ActualQuantity * model.ActualUnitPrice;

                    request.ActualQuantity = model.ActualQuantity;
                    request.ActualUnitPrice = model.ActualUnitPrice;

                    /* 呼叫DAO層 */
                    orderRecordDetailDAO.EditUseDetailId(model, request);

                    /* 紀錄資料 */
                    AddAffectData(data.BeforeData, "ModifiedOrderDetailData", request);

                    /* 檢查資料 */
                    if (!model.Success)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.SYSTEM_ERROR, model);
                        logRemark = model.Message;
                        return;
                    }

                    #endregion

                    #region 更新訂單金額

                    /* 更新訂單付款金額 */
                    if (originalPrice != newPrice)
                    {
                        model.Success = EditOrderRecordPayAmount(request2, originalPrice - newPrice);
                    }

                    /* 紀錄資料 */
                    AddAffectData(data.BeforeData, "ModifiedOrderData", request2);

                    #endregion

                    /* 檢查資料 */
                    if (model.Success)
                    {
                        transaction.Commit();
                    }
                    else
                    {
                        transaction.Rollback();
                    }
                }
                catch (Exception e)
                {
                    logLevel = (SByte)LogLevel.Error;
                    logRemark = e.Message;
                    transaction.Rollback();
                    throw;
                }
                finally
                {
                    /* 新增Log */
                    AddLog(logLevel, logType, model, logRemark, data);
                }
            }
        }

        /// <summary>
        /// 訂單詳情刪除(押金審核後禁止刪除一般單，補單可刪除)
        /// </summary>
        public void DeleteOrderRecordDetail(OrderRecordDetailRequest<String> model)
        {
            using (var transaction = BeginTransaction())
            using (orderRecordDetailDAO)
            {
                /* Log相關資料 */
                SByte logLevel = (SByte)LogLevel.Failure;
                Int32 logType = (Int32)LogRecordLogType.CardOrder_Child_Delete;
                String logRemark = "";

                LogAffectData data = new LogAffectData();

                try
                {
                    #region 驗證訂單、子訂單

                    /* 獲取訂單詳情資料 */
                    OrderRecordDetail request = GetOrderRecordDetail(model.DetailID);

                    /* 紀錄資料 */
                    AddAffectData(data.AfterData, "OriginalOrderDetailData", request);

                    /* 檢查資料 */
                    if (request == null)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_DETAIL_DELETE_CANNOT_FIND_DATA, model);
                        return;
                    }

                    /* 確認用戶關聯性 */
                    if (request.CreateUid != model.CreateUID && !CheckUserRelevance(request.CreateUid, model.CompanyID))
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_DETAIL_DELETE_NO_DATA_OWNERSHIP, model);
                        return;
                    }

                    /* 獲取訂單資料 */
                    OrderRecord request2 = GetOrderRecord(request.OrderNo);

                    /* 紀錄資料 */
                    AddAffectData(data.AfterData, "OriginalOrderData", request2);

                    /* 檢查資料 */
                    if (request2 == null)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_DETAIL_DELETE_CANNOT_FIND_DATA, model);
                        return;
                    }

                    /* 若押金已審核則只能刪除補單，無法刪除一般單 */
                    if (request2.DepositUid > 0 && request.OrderQuantity > 0)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.ORDER_DETAIL_DELETE_PAY_PASSED, model);
                        return;
                    }

                    #endregion

                    #region 刪除子訂單

                    /* 呼叫DAO層 */
                    orderRecordDetailDAO.DeleteUseDetailId(model, request);

                    /* 檢查資料 */
                    if (!model.Success)
                    {
                        statusCodeFactory.BuildStatus(StatusCode.SYSTEM_ERROR, model);
                        logRemark = model.Message;
                        return;
                    }

                    #endregion

                    #region 更新訂單金額

                    /* 更新訂單付款金額 */
                    Decimal price = request.ActualQuantity * request.ActualUnitPrice;
                    if (price > 0)
                    {
                        model.Success = EditOrderRecordPayAmount(request2, price);
                    }

                    /* 紀錄資料 */
                    AddAffectData(data.BeforeData, "ModifiedOrderData", request2);

                    #endregion

                    /* 檢查資料 */
                    if (model.Success)
                    {
                        transaction.Commit();
                    }
                    else
                    {
                        transaction.Rollback();
                    }
                }
                catch (Exception e)
                {
                    logLevel = (SByte)LogLevel.Error;
                    logRemark = e.Message;
                    transaction.Rollback();
                    throw;
                }
                finally
                {
                    /* 新增Log */
                    AddLog(logLevel, logType, model, logRemark, data);
                }
            }
        }

        /// <summary>
        /// 訂單詳情列表(需要優化)
        /// </summary>
        public void GetOrderRecordDetail(OrderRecordDetailRequest<List<OrderRecordDetailResponse>> model)
        {
            using (orderRecordDetailDAO)
            {
                /* 轉換Model */
                OrderRecordDetail request = MapperRequest(model);
                BaseModel<List<OrderRecordDetail>> _model = new BaseModel<List<OrderRecordDetail>>
                {
                    PageIndex = model.PageIndex,
                    PageSize = model.PageSize
                };

                /* 呼叫DAO層 */
                orderRecordDetailDAO.Get(_model, request);

                if (!_model.Success)
                {
                    return;
                }

                /* 確認用戶關聯性 */
                if (_model.Result.Count > 0)
                {
                    if (_model.Result[0].CreateUid != model.CreateUID && !CheckUserRelevance(_model.Result[0].CreateUid, model.CompanyID))
                    {
                        return;
                    }
                }

                BaseModel<List<BankInfo>> model2 = new BaseModel<List<BankInfo>>();
                BankInfoRequest request2 = new BankInfoRequest();
                request2.BankCodes = _model.Result.Select(d => d.BankCode).ToList();

                /* 呼叫DAO層 */
                bankInfoDAO.Get(model2, request2);

                /* 檢查資料 */
                if (!model2.Success)
                {
                    return;
                }

                Dictionary<String, String> bank = new Dictionary<String, String>();
                foreach (BankInfo cardMerchant in model2.Result)
                {
                    bank.Add(cardMerchant.BankCode, cardMerchant.BankName);
                }

                /* 轉換Model */
                OrderRecordDetailResponse temp;
                List<OrderRecordDetailResponse> result = new List<OrderRecordDetailResponse>();
                foreach (OrderRecordDetail __model in _model.Result)
                {
                    temp = MapperResponse(__model);

                    if (bank.ContainsKey(temp.BankCode))
                    {
                        temp.BankName = bank[temp.BankCode];
                    }

                    result.Add(temp);
                }

                /* 結果複製 */
                model.Result = result;
                model.Success = _model.Success;
                model.TotalCount = _model.TotalCount;
            }
        }

        /// <summary>
        /// 訂單付款金額修改
        /// </summary>
        private Boolean EditOrderRecordPayAmount(OrderRecord query, Decimal price)
        {
            BaseModel<String> model = new BaseModel<String>();

            query.PayAmount -= price;

            /* 呼叫DAO層 */
            orderRecordDAO.EditUseOrderNo(model, query);

            return model.Success;
        }

        /// <summary>
        /// 訂單取得
        /// </summary>
        private OrderRecord GetOrderRecord(Int64 orderNo)
        {
            BaseModel<List<OrderRecord>> model = new BaseModel<List<OrderRecord>>();
            Entity.DAORequest.Order.OrderRecordRequest request = new Entity.DAORequest.Order.OrderRecordRequest();
            request.OrderNo = orderNo;
            request.ExactMatch = true;

            /* 呼叫DAO層 */
            orderRecordDAO.Get(model, request);

            /* 檢查資料 */
            if (!model.Success || model.Result.Count != 1)
            {
                return null;
            }

            return model.Result[0];
        }

        /// <summary>
        /// 訂單詳情取得
        /// </summary>
        private OrderRecordDetail GetOrderRecordDetail(Int32 detailId)
        {
            BaseModel<List<OrderRecordDetail>> model = new BaseModel<List<OrderRecordDetail>>();
            OrderRecordDetail query = new OrderRecordDetail();
            query.DetailId = detailId;

            /* 呼叫DAO層 */
            orderRecordDetailDAO.Get(model, query);

            /* 檢查資料 */
            if (!model.Success || model.Result.Count != 1)
            {
                return null;
            }

            return model.Result[0];
        }

        /// <summary>
        /// 訂單詳情取得
        /// </summary>
        private List<OrderRecordDetail> GetOrderRecordDetails(OrderRecordDetail request)
        {
            BaseModel<List<OrderRecordDetail>> model = new BaseModel<List<OrderRecordDetail>>();

            /* 呼叫DAO層 */
            orderRecordDetailDAO.Get(model, request);

            /* 檢查資料 */
            if (!model.Success)
            {
                return null;
            }

            return model.Result;
        }

        /// <summary>
        /// 訂單詳情數取得
        /// </summary>
        private Int32? GetOrderRecordDetailCount(OrderRecordDetail request)
        {
            List<OrderRecordDetail> list = GetOrderRecordDetails(request);

            /* 檢查資料 */
            if (list == null)
            {
                return null;
            }

            return list.Count;
        }

        /// <summary>
        /// 未授權銀行卡取得
        /// </summary>
        private List<BankCard> GetBankCards(Int64 orderNo)
        {
            return bankCardDAO.GetList(new Entity.Parameter.BankCardQuery()
            {
                OrderNo = orderNo,
                EnableStatus = (SByte)BankCardEnableStatus.未授权
            });
        }

        /// <summary>
        /// 資料庫交易
        /// </summary>
        protected virtual IDbContextTransaction BeginTransaction()
        {
            return this.dbContext.Database.BeginTransaction();
        }

        /// <summary>
        /// 紀錄Log相關資料
        /// </summary>
        private void AddAffectData(Dictionary<String, Object> affectData, String key, OrderRecord model)
        {
            ICollection<OrderRecordDetail> temp = model.OrderRecordDetail;
            model.OrderRecordDetail = null;
            affectData.Add(key, CloneObject(model));
            model.OrderRecordDetail = temp;
        }

        private void AddAffectData(Dictionary<String, Object> affectData, String key, OrderRecordDetail model)
        {
            OrderRecord temp = model.OrderNoNavigation;
            model.OrderNoNavigation = null;
            affectData.Add(key, CloneObject(model));
            model.OrderNoNavigation = temp;
        }

        private void AddAffectData(Dictionary<String, Object> affectData, String key, List<OrderRecordDetail> models)
        {
            List<OrderRecordDetail> list = new List<OrderRecordDetail>();
            OrderRecord temp = null;
            foreach (OrderRecordDetail model in models)
            {
                temp = model.OrderNoNavigation;
                model.OrderNoNavigation = null;
                list.Add(CloneObject(model));
                model.OrderNoNavigation = temp;
            }

            affectData.Add(key, list);
        }

        //检查是否是卡管专员
        private bool CheckCardUser(List<int> cmList,int userId)
        {
            bool isCheck = false;
            BaseModel<List<CardMerchant>> model5 = new BaseModel<List<CardMerchant>>();
            CardMerchantRequest request5 = new CardMerchantRequest();
            request5.CMID = cmList;

            cardMerchantDAO.Get2(model5, request5);

            if (model5.Success && model5.Result.Count>0)
            {
                if (model5.Result[0].CreateUid == userId)
                {
                    isCheck = true;
                }
            }
            return isCheck;
        }
    }
}
